package com.swd.order.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.swd.order.model.User;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final String SECRET="my_secret";

    private static final long EXPIRATION= 3600L;

    public static String createToken(User user){
        Date expireDate=new Date(System.currentTimeMillis()+EXPIRATION*1000)  ;
        Map<String,Object> map=new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        String token= JWT.create()
                .withHeader(map)
//                .withClaim("id",user.getId())
                .withClaim("name",user.getName())
                .withExpiresAt(expireDate)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }
    public static DecodedJWT verifyToken(String token){
        DecodedJWT jwt=null;
        try {
            JWTVerifier verifier=JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt=verifier.verify(token);
        }
        catch (Exception e){

            return  null;
        }
        return jwt;
    }

    public static String createToken(String key){
        Map<String,Object> map=new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        String token= JWT.create()
                .withHeader(map)
                .withClaim("id",key)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public static void main(String[] args) {
        System.out.println("createToken(\"swd-order\") = " + createToken("swd-order"));
    }
}
